package restful;

import static java.text.MessageFormat.*;

import java.util.*;

public class Methods {

	private static boolean hasParametersOrAmp(String queryString) {
		if (queryString.matches("^[^=&]*$")) return true;
		if (queryString.matches("^[^=&]*&+$")) return true;
		if (queryString.matches("^&+[^=&]*&+$")) return true;
		return false;
	}

	public static final String methodOf(String queryString) {
		if (queryString == null) return "";
		if ("".equals(queryString)) return "";
		if (hasParametersOrAmp(queryString)) return withoutAmp(queryString);
		return "";
	}

	public static final List<String> methodsOf(RestfulProtocol protocol) {
		List<String> strings = new LinkedList<String>();
		for (RestfulMethod method : protocol.getMethods()) {
			strings.add(method.toString());
		}
		return strings;
	}

	public static final List<String> resourcesOf(RestfulProtocol protocol) {
		List<String> strings = new LinkedList<String>();
		for (RestfulResource resource : protocol.getResources()) {
			strings.add(resource.getName());
		}
		return strings;
	}

	private static String withoutAmp(String queryString) {
		return format("!{0}", queryString.replaceAll("&", ""));
	}
}
